package main

import (
	"flag"
	"fmt"
	"io"
	"net"
	"os"
	"time"
)

// Client 客户端类型
type Client struct {
	// 服务端IP
	ServerIP string
	// 服务端端口
	ServerPort int
	// 客户端名称
	Name string
	// 客户端的连接
	conn net.Conn
	// 当前客户端的模式
	flag int
}

// NewClient 建立一个客户端
func NewClient(serverIP string, serverPort int) *Client {
	// 创建客户端对象
	client := &Client{
		ServerIP:   serverIP,
		ServerPort: serverPort,
		flag:       999,
	}

	// 连接Server
	conn, err := net.Dial("tcp", fmt.Sprintf("%s:%d", serverIP, serverPort))
	if err != nil {
		fmt.Println("net.Dial error:", err)
		return nil
	}
	client.conn = conn

	// 返回对象
	return client
}

func (c *Client) menu() bool {
	time.Sleep(time.Second * 1)
	var flag int
	fmt.Println("1.公聊模式")
	fmt.Println("2.私聊模式")
	fmt.Println("3.更改用户名")
	fmt.Println("0.退出")
	fmt.Scan(&flag)

	if flag >= 0 && flag <= 3 {
		c.flag = flag
		return true
	} else {
		fmt.Println(">>>>>>>请输入合法范围内的数字<<<<<<<")
		return false
	}
}

// UpdateName 更新用户名
func (c *Client) UpdateName() bool {
	fmt.Println(">>>>>>>请输入用户名:")
	fmt.Scan(&c.Name)

	sendMsg := "rename|" + c.Name + "\n"
	_, err := c.conn.Write([]byte(sendMsg))
	if err != nil {
		fmt.Println("conn Write error:", err)
		return false
	}
	return true
}

// PublicChat 公聊模式
func (c *Client) PublicChat() {
	// 提示用户输入消息
	var chatMsg string
	fmt.Println(">>>>>>>请输入聊天内容,exit退出.")
	fmt.Scan(&chatMsg)

	for chatMsg != "exit" {
		if len(chatMsg) > 0 {
			sendMsg := chatMsg + "\n"
			_, err := c.conn.Write([]byte(sendMsg))
			if err != nil {
				fmt.Println("conn Write error:", err)
				break
			}
		}
		time.Sleep(time.Second * 1)
		chatMsg = ""
		fmt.Println(">>>>>>>请输入聊天内容,exit退出:")
		fmt.Scan(&chatMsg)
	}
}

// PrivateChat 私聊模式
func (c *Client) PrivateChat() {
	var remoteName string
	var chatMsg string
	c.SelectUsers()
	fmt.Println(">>>>>>>请输入聊天对象[用户名],exit退出:")
	fmt.Scan(&remoteName)

	for remoteName != "exit" {
		fmt.Println(">>>>>>>请输入聊天内容,exit退出:")
		fmt.Scan(&chatMsg)
		for chatMsg != "exit" {
			if len(chatMsg) != 0 {
				sendMsg := "to|" + remoteName + "|" + chatMsg + "\n"
				_, err := c.conn.Write([]byte(sendMsg))
				if err != nil {
					fmt.Println("conn Write error:", err)
					break
				}
			}
			time.Sleep(time.Second * 1)
			chatMsg = ""
			fmt.Println(">>>>>>>请输入聊天内容,exit退出:")
			fmt.Scan(&chatMsg)
		}
		time.Sleep(time.Second * 1)
		c.SelectUsers()
		remoteName = ""
		fmt.Println(">>>>>>>请输入聊天对象[用户名],exit退出:")
		fmt.Scan(&remoteName)
	}
}

// SelectUsers 查询在线用户
func (c *Client) SelectUsers() {
	sendMsg := "who\n"
	_, err := c.conn.Write([]byte(sendMsg))
	if err != nil {
		fmt.Println("conn Write error:", err)
		return
	}
}

// Run 客户端的主业务
func (c *Client) Run() {
	for c.flag != 0 {
		// 用户输入正确时结束循环
		for c.menu() != true {
		}

		switch c.flag {
		case 1:
			// 公聊模式
			c.PublicChat()
			break
		case 2:
			// 私聊模式
			c.PrivateChat()
			break
		case 3:
			// 更新用户名
			c.UpdateName()
			break
		}
	}
}

// DealResponse 处理Server回应的消息,直接显示到标准输出即可
func (c *Client) DealResponse() {
	// 一旦client.conn有数据,就直接copy到stout标准输出上,永久阻塞监听
	io.Copy(os.Stdout, c.conn)
	// 上面等同于下面
	/*for {
		buf := make([]byte, 4096)
		c.conn.Read(buf)
		fmt.Println(buf)
	}*/
}

var serverIP string
var serverPort int

// 初始化解析命令行,格式: ./client -ip 127.0.0.1 -port 8888
func init() {
	flag.StringVar(&serverIP, "ip", "127.0.0.1", "设置服务器IP地址(默认是127.0.0.1)")
	flag.IntVar(&serverPort, "port", 8888, "设置服务器端口(默认是8888)")
}

func main() {
	// 命令行解析
	flag.Parse()

	client := NewClient(serverIP, serverPort)
	if client == nil {
		fmt.Println(">>>>>>>连接服务器失败...")
		return
	}

	// 单独开启一goroutine去处理server的回执消息
	go client.DealResponse()

	fmt.Printf(">>>>>>>成功连接服务器%s:%d\n", client.ServerIP, client.ServerPort)

	// 启动客户端业务
	client.Run()
}
